var superagent = require("superagent");
var cheerio = require("cheerio");

var url = "http://dig.chouti.com";
var page_url = url + "/all/hot/recent/";

function index(req, res){
    superagent.get(url).end(function(err, sres){
        
        var items = cheerioQuery(sres.text);

        res.render("site/index", items, function(err, html){
            res.send(html);
        });
    });
}

function page(req, res){
    superagent.get(page_url + req.query.p).end(function(err, sres){

        var items = cheerioQuery(sres.text);

        res.render("site/index", items, function(err, html){
            res.send(html);
        });
    });
}

function cheerioQuery(data){
    let $ = cheerio.load(data);
    let items = {
        content_list : [],
        page : 0,
        front_page : 0,
        next_page : 0
    }

    $("#content-list .news-content").each(function(index, elem){
        var $elem = $(elem);

        let part1 = $elem.children(".part1");
        let part2 = $elem.children(".part2");

        items.content_list.push({
            href : part1.children(".show-content").attr("href"),
            title : part2.attr("share-title"),
            img : part2.attr("share-pic")
        });
    });

    items.page = $("#page-area .ct_pagepw").text().trim();
    items.front_page = items.page != 1 ? Number(items.page) - 1 : false;
    items.next_page = Number(items.page) + 1;
    
    return items;
}

exports.index = index;
exports.page = page;